// 解析Http响应
interface ResponseMessage {
  header: {
    statusLine: string;
    headerSegment: {
      [propName: string]: any;
    };
  };
  body: string;
}

const responseMessage: ResponseMessage = {
  header: {
    statusLine: "",
    headerSegment: {},
  },
  body: "",
};

function receive(string: string) {
  let segmentNameTemp = "";
  let segmentValueTemp = "";

  const waitingBody = (c: string) => {
    // 接收报文主体，不考虑transfer-coding
    responseMessage.body += c;
    return waitingBody;
  };
  const waitingHeaderBlockEnd = (c: string) => {
    if (c === "\n") {
      return waitingBody;
    }
    throw new Error("The format of the response message is incorrect");
  };

  // 读到首部字段一行结尾，return字符串
  const waitingHeaderLineEnd = (c: string) => {
    if (c === "\n") {
      return c;
    }
    throw new Error("The format of the response message is incorrect");
  };

  const waitingHeaderValue = (c: string) => {
    if (c === "\r") {
      responseMessage.header.headerSegment[segmentNameTemp] = segmentValueTemp;
      segmentNameTemp = "";
      segmentValueTemp = "";
      return waitingHeaderLineEnd;
    }
    segmentValueTemp += c;
    return waitingHeaderValue;
  };

  const waitingHeaderSpace = (c: string) => {
    if (c === " ") {
      return waitingHeaderValue;
    }
    throw new Error("The format of the response message is incorrect");
  };

  function waitingHeaderName(c: string) {
    if (c === ":") {
      return waitingHeaderSpace;
    }
    if (c === "\r") {
      return waitingHeaderBlockEnd;
    }
    segmentNameTemp += c;
    return waitingHeaderName;
  }

  const waitingStatusLineEnd = (c: string) => {
    if (c === "\n") {
      return waitingHeaderName;
    }
    throw new Error("The format of the response message is incorrect");
  };

  const waitingStatusLine = (c: string) => {
    if (c === "\r") {
      return waitingStatusLineEnd;
    }
    responseMessage.header.statusLine += c;
    return waitingStatusLine;
  };

  let state = waitingStatusLine;

  string.split("").forEach((char: string) => {
    state = state(char);
    if (typeof state === "string") {
      // 上一个 state 为waitingHeaderLineEnd，返回一个字符串
      // 代表要重新读下一行首部字段
      state = waitingHeaderName;
    }
  });
}

// 解析响应的http报文
export default function parseResponse(data: string) {
  // 使用有限状态机响应报文（用函数表示状态）
  receive(data);
  return responseMessage;
}
